<?php
class SimpleMySQLObject{

	function connect($sqlserver, $sqluser, $sqlpassword, $database){
		$this->connect_id = mysql_connect($sqlserver, $sqluser, $sqlpassword);
		if($this->connect_id){
			if (mysql_select_db($database)){
				return $this->connect_id;
			}else{
				$this->error();
				return null;
			}
		}else{
			$this->error();
			return null;
		}
	}

	function error(){
		if(mysql_error() != ''){
			echo '<b>MySQL Error</b>: '.mysql_error().'<br/>';
		}
	}

	function query($query){
		if ($query != NULL){
			$this->query_result = mysql_query($query, $this->connect_id);
			if(!$this->query_result){
				$this->error();
				return null;
			}else{
				return $this->query_result;
			}
		}else{
			return '<b>MySQL Error</b>: Empty Query!';
		}
	}

	function countResults($query_id = ""){
		if($query_id == NULL){
			if ($this->query_result) $return = mysql_num_rows($this->query_result);
			else return 0;
		}else{
			$return = mysql_num_rows($query_id);
		}
		if(!$return){
			$this->error();
		}else{
			return $return;
		}
	}

	function fetchRow($query_id = ""){
		if($query_id == NULL){
			$return = mysql_fetch_object($this->query_result); 
		}else{
			$return = mysql_fetch_object($query_id);
		}
		if(!$return){
			$this->error();
		}else{
			return $return;
		}
	}    

	function getAffectedRows($query_id = ""){
		if($query_id == NULL){
			$return = mysql_affected_rows($this->query_result); 
		}else{
			$return = mysql_affected_rows($query_id);
		}
		if(!$return){
			$this->error();
		}else{
			return $return;
		}
	}

	function results($query_id = "") {
		$results = array();
		$c = $this->countResults();

		for ($i=0;$i<$c; $i++) {
			$row = $this->fetchRow($query_id);
			$results[$i] = $row;
		}

		return $results;
	}

	function disconnect(){
		if($this->connect_id){
			return mysql_close($this->connect_id);
		}
	}

	function tableExists($tname) { //why not just return the results?  I wanted explicity true/false, so sue me.
		if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$tname."'", $this->connect_id))) return true;
		else return false;
	}

	function runSQLFile($filepath) {
		$queryF = file_get_contents($filepath);
		$queryF = str_replace('\t',' ', $queryF);
		$queryF = str_replace('\n','', $queryF);
		$queryF = str_replace('\r','', $queryF);
		$queryF = explode(";",$queryF);
		foreach($queryF as $query) {
			$query = trim($query);
			if ($query) {
				$result = mysql_query($query);
				if ($result == false) $this->error();
			}
		}
	}
}
?>